﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;

namespace DbToJson
{
    using System.IO;

    using Dapper;

    using Newtonsoft.Json;

    class Program
    {
        static void Main(string[] args)
        {
            string inputFilePath = args[0];
            var inputFile = new FileInfo(inputFilePath);
            var directory = inputFile.Directory;
            var outputFilePath = Path.Combine(directory.FullName, "data.txt");

            SQLiteConnection connection = new SQLiteConnection("Data Source=" + inputFilePath);

            var data = connection.Query("select * from person");
            var serializeObject = JsonConvert.SerializeObject(data);
            var byteArray = Encoding.UTF8.GetBytes(serializeObject);
            var result = Convert.ToBase64String(byteArray);
            var resultByte = Encoding.UTF8.GetBytes(result);

            // File.WriteAllText(outputFilePath, result, Encoding.UTF8);


            FileStream fileStream = new FileStream(outputFilePath, FileMode.Create);
            fileStream.Write(resultByte, 0, resultByte.Length);
            fileStream.Close();

            fileStream = new FileStream(outputFilePath, FileMode.Open);


            int count = 0;
            long length = fileStream.Length;
            byte[] receiveStream = new byte[length];

            while (true)
            {
                int readLength = fileStream.Length - count > 1000 ? 1000 : (int)fileStream.Length - count;
                int num = fileStream.Read(receiveStream, count, readLength);
                if (num == 0) break;

                count += num;
            }

            var receive1 = Encoding.UTF8.GetString(receiveStream, 0, (int)length);

            var byteValue1 = Convert.FromBase64String(receive1);
            string decodeReceive1 = Encoding.UTF8.GetString(byteValue1, 0, byteValue1.Length);

            if (decodeReceive1 == serializeObject)
            {
                Console.WriteLine("Convert complete.");
                Console.ReadLine();
            }

            fileStream.Close();
        }
    }
}
